import axios from "axios";
import type { AxiosInstance, AxiosError, AxiosRequestConfig } from "axios";
import { errorMsg } from "./message";

// API响应类型定义
export interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
  status: string;
}

// 创建实例
export const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers!.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError) => Promise.reject(error)
);

// 响应拦截器（类型安全）
instance.interceptors.response.use(
  (response) => {
    // 声明返回Promise<T>
    if(response.data.code === 200) {
      return response.data.data; // 现在类型匹配
    }else if (response.data.code === 401) {
      localStorage.clear()
      return Promise.reject(response);
    }else {
      return Promise.reject(response);
    }
  },
  (error: AxiosError) => {
    console.log(JSON.stringify(error) +'------');
    
    // 网络错误处理
    if (!error.response) {
      error.message = "网络连接异常，请检查网络设置";
    }
    return Promise.reject(error);
  }
);

// 封装工具函数
export const api = {
  get: async <T, P = Record<string, unknown>>(
    url: string,
    params?: P,
    config?: AxiosRequestConfig
  ) => {
    const res = await instance.get<never, T>(url, { params, ...config });
    return res; // 类型自动推断为T
  },

  post: async <T, D = Record<string, unknown>>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig
  ) => {
    const res = await instance.post<never, T>(url, data, config);
    return res; // 类型自动推断为T
  },

  delete: async <T, D = Record<string, unknown>>(
    url: string,
    config?: AxiosRequestConfig<D>
  ) => {
    const res = await instance.delete<never, T>(url, config);
    return res; // 类型自动推断为T
  },
};
